package com.legleg.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 12-12-31
 * Time: 上午12:07
 * To change this template use File | Settings | File Templates.
 */
public class DownLoadUtil {
    public static boolean download(DownLoadObject down){
        int byteread = 0;
        URL url;
        URLConnection conn;
        InputStream inStream;
        FileOutputStream fs;
        File picfile = null;
        try {
            String filename = FilenameUtils.concat(down.getDir(), down.getRename());
            picfile = new File(filename);
            if(picfile.exists()) return true;
            FileUtils.touch(picfile);
            url = new URL(down.getUrl());
            conn = url.openConnection();
            conn.setConnectTimeout(10000);
            inStream = conn.getInputStream();
            fs = new FileOutputStream(filename);

            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteread);
            }
            System.out.println("done "+down.getDir()+"\\"+down.getRename());
        }catch (Exception e) {
            try {
                picfile.deleteOnExit();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            return false;
        }finally {
            url = null;
            conn = null;
            inStream = null;
            fs = null;
        }
        return true;
    }
}
